<?php

namespace app\api\model;

use app\api\validate\UserAddress;
use think\Model;


class UserAddressModel extends ApiModel
{
    // 表名
    protected $name = 'user_address';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    public function getAddressList($params = array()){
        $list = self::where(['member_id' => $params['uid']])
            ->order('id desc')
            ->field('id,real_name,phone,region,address,is_default')
            ->select();
        return $this->api_success('获取成功',$list);
    }


    public function addAddress($params = array())
    {
        //验证数据
        $userAddressValidator = new UserAddress();
        if (!$userAddressValidator->scene('add')->check($params)) {
            return $this->api_error($userAddressValidator->getError());
        }
        $params['member_id'] = $params['uid'];
        //添加
        if (!self::allowField(true)->save($params)) {
            return $this->api_error('添加失败，请重新尝试');
        }
        return $this->api_success('添加成功');
    }


    public function updateAddress($params = array())
    {
        //验证数据
        $userAddressValidator = new UserAddress();
        if (!$userAddressValidator->scene('update')->check($params)) {
            return $this->api_error($userAddressValidator->getError());
        }
        $address = self::where(['id' => $params['id']])->find();
        if (!$address) {
            return $this->api_error('数据不存在');
        }
        $address->real_name = $params['real_name'];
        $address->phone = $params['phone'];
        $address->region = $params['region'];
        $address->address = $params['address'];
        //添加
        if (!$address->save()) {
            return $this->api_error('修改失败，请重新尝试');
        }
        return $this->api_success('修改成功');
    }

    public function deleteAddress($params = array())
    {
        $address = self::where(['id' => $params['id']])->find();
        if (!$address) {
            return $this->api_error('数据不存在');
        }
        if (!$address->delete()) {
            return $this->api_error('删除失败，请重新尝试');
        }
        return $this->api_success('删除成功');
    }

}
